package com.zmxstudy.gzu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zmxstudy.gzu.domain.TbBrand;
import com.zmxstudy.gzu.mapper.TbBrandMapper;
import com.zmxstudy.gzu.utils.ProductCodeMsg;
import com.zmxstudy.gzu.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "品牌管理")
@RestController
@RequestMapping("/product-service/brands")
@SuppressWarnings("rawtypes")
public class BrandController {

    @Resource
    TbBrandMapper tbBrandMapper;

    //添加品牌
    @Operation(summary = "新增平品牌条目")
    @PostMapping
    public Result addBrand(@RequestBody TbBrand brand) {
        LambdaQueryWrapper<TbBrand> laq = new LambdaQueryWrapper<>();
        laq.eq(TbBrand::getName, brand.getName());
        List<TbBrand> list = tbBrandMapper.selectList(laq);
        if (list.size() > 0) {
            return Result.error(ProductCodeMsg.UPDATEBrand_error);
        }
        brand.setId(null);
        tbBrandMapper.insert(brand);
        return Result.success();
    }

    @Operation(summary = "查询品牌")
    @GetMapping("/{id}")
    Result findBrand(@PathVariable Long id) {
        if (id == null) {
            return Result.error(ProductCodeMsg.SELECTBrand_error);
        }

        TbBrand brand = tbBrandMapper.selectById(id);
        if (brand == null) {
            return Result.error(ProductCodeMsg.SELECTBrand_error);
        }
        return Result.success("品牌查询成功", brand);
    }

    @Operation(summary = "查询所有")
    @GetMapping()
    Result<List<TbBrand>> findBrand() {
        List<TbBrand> list = tbBrandMapper.selectList(null);
        return Result.success("品牌查询成功", list);
    }


    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    public Result deleteBrand(@PathVariable long id) {
        tbBrandMapper.deleteById(id);
        return Result.success();
    }

    @Operation(summary = "修改")
    @PutMapping
    public Result updateBrand(@RequestBody TbBrand brand) {
        tbBrandMapper.updateById(brand);
        return Result.success();
    }
}
